package com.example.threadmodel.service;

import com.example.threadmodel.model.NamedPoolThreadFactory;
import lombok.Getter;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class HashThreadManagerService {
    private final static int THREAD_NUM = 32;
    public final static String ACTION_THREAD_NAME_PREFIX = "HASH_THREAD-";

    @Getter
    private ExecutorService[] actionExecutors = new ExecutorService[THREAD_NUM];


    public void init() {
        for (int i = 0; i < THREAD_NUM; i++) {
            actionExecutors[i] = Executors.newSingleThreadExecutor(new NamedPoolThreadFactory(ACTION_THREAD_NAME_PREFIX));
        }
    }

    public void addTask(int hashId, Runnable runnable) {
        int index = Math.abs(hashId % THREAD_NUM);
        actionExecutors[index].execute(runnable);
    }

}
